"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const mobx_miniprogram_bindings_1 = require("mobx-miniprogram-bindings");
const index_1 = require("../../../store/index");
const auth_1 = require("../../../services/auth");
const profile_1 = require("../../../services/profile");
const toast_1 = require("../../../utils/toast");
const tabBar_1 = require("../../../utils/tabBar");
Page({
    data: {
        user: index_1.globalStore.userProfile,
        isChef: index_1.globalStore.isChef,
        chefStats: {
            topDish: "暂无数据",
            topCount: 0,
            bestRatedDish: "暂无数据",
            bestRatedScore: "--",
            lowestDish: "暂无数据",
            lowestCount: 0,
        },
    },
    storeBindings: null,
    onLoad() {
        this.storeBindings = (0, mobx_miniprogram_bindings_1.createStoreBindings)(this, {
            store: index_1.globalStore,
            fields: ["userProfile"],
        });
    },
    onUnload() {
        var _a, _b;
        (_b = (_a = this.storeBindings) === null || _a === void 0 ? void 0 : _a.destroyStoreBindings) === null || _b === void 0 ? void 0 : _b.call(_a);
    },
    onShow() {
        return __awaiter(this, void 0, void 0, function* () {
            yield index_1.globalStore.initAppData();
            const isChef = index_1.globalStore.isChef;
            this.setData({ isChef, user: index_1.globalStore.userProfile });
            (0, tabBar_1.applyTabBar)(isChef ? "chef" : index_1.globalStore.isDiner ? "diner" : "guest");
            if (!index_1.globalStore.userProfile) {
                wx.redirectTo({ url: "/pages/auth/login/index" });
                return;
            }
            if (isChef) {
                this.refreshChefStats();
            }
        });
    },
    handleGoOrders() {
        if (this.data.isChef) {
            wx.switchTab({ url: "/pages/user/cart/index" });
        }
        else {
            wx.switchTab({ url: "/pages/user/cart/index" });
        }
    },
    handleGoCart() {
        wx.switchTab({ url: "/pages/user/cart/index" });
    },
    handleLogout() {
        wx.showModal({
            title: "退出登录",
            content: "确定要离开甜蜜厨房吗？",
            success: (res) => __awaiter(this, void 0, void 0, function* () {
                if (!res.confirm)
                    return;
                try {
                    yield (0, auth_1.logout)();
                }
                catch (error) {
                    console.error("logout failed", error);
                }
                finally {
                    index_1.globalStore.logout();
                    (0, toast_1.toast)("已退出");
                    (0, tabBar_1.applyTabBar)("guest");
                    wx.redirectTo({ url: "/pages/auth/login/index" });
                }
            }),
        });
    },
    handleChangeAvatar() {
        wx.chooseImage({
            count: 1,
            sizeType: ["compressed"],
            sourceType: ["album", "camera"],
            success: (res) => __awaiter(this, void 0, void 0, function* () {
                var _a;
                const filePath = (_a = res.tempFilePaths) === null || _a === void 0 ? void 0 : _a[0];
                if (!filePath)
                    return;
                try {
                    const result = yield (0, profile_1.updateProfile)({ avatarUrl: filePath });
                    index_1.globalStore.setUserProfile(result.user);
                    (0, toast_1.toast)("头像已更新");
                }
                catch (error) {
                    console.error("update avatar failed", error);
                    wx.showToast({ title: "更新失败", icon: "none" });
                }
            }),
            fail: (err) => {
                var _a;
                if ((_a = err === null || err === void 0 ? void 0 : err.errMsg) === null || _a === void 0 ? void 0 : _a.includes("cancel"))
                    return;
                console.error("choose image failed", err);
                wx.showToast({ title: "无法选择图片", icon: "none" });
            },
        });
    },
    refreshChefStats() {
        if (!this.data.isChef)
            return;
        const menuList = index_1.globalStore.menu || [];
        const statsMap = new Map();
        menuList.forEach((item) => {
            statsMap.set(item._id, {
                name: item.name,
                count: 0,
                ratingTotal: 0,
                ratingCount: 0,
            });
        });
        (index_1.globalStore.orders || []).forEach((order) => {
            order.items.forEach((item) => {
                if (!statsMap.has(item.menuId)) {
                    statsMap.set(item.menuId, {
                        name: item.name,
                        count: 0,
                        ratingTotal: 0,
                        ratingCount: 0,
                    });
                }
                const entry = statsMap.get(item.menuId);
                entry.count += Math.max(1, Number(item.quantity) || 1);
                if (order.review) {
                    entry.ratingTotal += order.review.rating;
                    entry.ratingCount += 1;
                }
            });
        });
        const records = Array.from(statsMap.entries());
        if (!records.length) {
            this.setData({
                chefStats: {
                    topDish: "暂无数据",
                    topCount: 0,
                    bestRatedDish: "暂无数据",
                    bestRatedScore: "--",
                    lowestDish: "暂无数据",
                    lowestCount: 0,
                },
            });
            return;
        }
        const topEntry = records.reduce((prev, curr) => curr[1].count > prev[1].count ? curr : prev);
        const lowestEntry = records.reduce((prev, curr) => curr[1].count < prev[1].count ? curr : prev);
        const ratedEntries = records.filter(([, value]) => value.ratingCount > 0);
        const bestEntry = ratedEntries.length
            ? ratedEntries.reduce((prev, curr) => {
                const prevAvg = prev[1].ratingTotal / prev[1].ratingCount;
                const currAvg = curr[1].ratingTotal / curr[1].ratingCount;
                return currAvg > prevAvg ? curr : prev;
            })
            : null;
        this.setData({
            chefStats: {
                topDish: topEntry[1].count ? topEntry[1].name : "暂无数据",
                topCount: topEntry[1].count,
                bestRatedDish: bestEntry ? bestEntry[1].name : "暂无数据",
                bestRatedScore: bestEntry
                    ? (bestEntry[1].ratingTotal / bestEntry[1].ratingCount).toFixed(1)
                    : "--",
                lowestDish: lowestEntry[1].name,
                lowestCount: lowestEntry[1].count,
            },
        });
    },
});
